"use client";

import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Form,
  Input,
  Select,
  Modal,
  Row,
  Col,
  Statistic,
  Spin,
  Alert,
  Drawer,
  Divider,
  Dropdown,
  MenuProps,
  App,
} from "antd";

const { TextArea } = Input;
import {
  PlusOutlined,
  ReloadOutlined,
  FilterOutlined,
  QuestionCircleOutlined,
  DownOutlined,
} from "@ant-design/icons";
import { system } from "@/forent-api/api";
import {
  getTableColumns,
  getLogTableColumns,
  formRules,
  getTaskConfigRules,
  TaskTypeMap,
  CommonCronExpressions,
  TaskConfigTemplates,
} from "./tools";

const { Option } = Select;

interface TimerTask {
  id?: number;
  task_name: string;
  task_code: string;
  cron_expression: string;
  task_type: string;
  task_config?: any;
  description?: string;
  status: number;
  isExecuting?: boolean; // 添加执行状态
}

interface TaskStats {
  totalCount: number;
  activeCount: number;
  inactiveCount: number;
  todayExecuteCount: number;
  todaySuccessCount: number;
  todayFailCount: number;
}

const SystemTimerContent: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [taskList, setTaskList] = useState<any[]>([]);
  const [taskTypes, setTaskTypes] = useState<any[]>([]);
  const [taskStats, setTaskStats] = useState<TaskStats>({
    totalCount: 0,
    activeCount: 0,
    inactiveCount: 0,
    todayExecuteCount: 0,
    todaySuccessCount: 0,
    todayFailCount: 0,
  });
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchForm] = Form.useForm();
  const [taskForm] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [logDrawerVisible, setLogDrawerVisible] = useState(false);
  const [editingTask, setEditingTask] = useState<TimerTask | null>(null);
  const [selectedTask, setSelectedTask] = useState<any>(null);
  const [logList, setLogList] = useState<any[]>([]);
  const [logPagination, setLogPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [selectedTaskType, setSelectedTaskType] = useState<string>("");
  const [isJavaScriptType, setIsJavaScriptType] = useState(false);

  const { message, modal } = App.useApp();

  // 初始化数据
  useEffect(() => {
    fetchTaskList();
    fetchTaskTypes();
    fetchTaskStats();
  }, []);

  // 处理任务类型变化
  const handleTaskTypeChange = (taskType: string) => {
    setSelectedTaskType(taskType);
    setIsJavaScriptType(taskType === "javascript");

    // 自动填充配置模板
    if (TaskConfigTemplates[taskType as keyof typeof TaskConfigTemplates]) {
      const template =
        TaskConfigTemplates[taskType as keyof typeof TaskConfigTemplates];
      if (taskType === "javascript" && "code" in template.config) {
        // JavaScript类型直接设置代码
        taskForm.setFieldValue("task_config", template.config.code);
      } else {
        // 其他类型设置JSON
        taskForm.setFieldValue(
          "task_config",
          JSON.stringify(template.config, null, 2)
        );
      }
    }
  };

  // 获取任务列表
  const fetchTaskList = async (params: any = {}) => {
    setLoading(true);
    try {
      const searchValues = searchForm.getFieldsValue();
      const result = await system.getTimerTaskList({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchValues,
        ...params,
      });

      if (result.code === 200) {
        setTaskList(result.data.list);
        setPagination({
          ...pagination,
          total: result.data.pagination.total,
          current: result.data.pagination.current,
        });
      }
    } catch (error) {
      message.error("获取任务列表失败");
    } finally {
      setLoading(false);
    }
  };

  // 获取任务类型
  const fetchTaskTypes = async () => {
    try {
      const result = await system.getTaskTypes();
      if (result.code === 200) {
        setTaskTypes(result.data);
      }
    } catch (error) {
      console.error("获取任务类型失败:", error);
    }
  };

  // 获取统计信息
  const fetchTaskStats = async () => {
    try {
      const result = await system.getTimerTaskStats();
      if (result.code === 200) {
        setTaskStats(result.data);
      }
    } catch (error) {
      console.error("获取统计信息失败:", error);
    }
  };

  // 获取任务日志
  const fetchTaskLogs = async (taskId: number, params: any = {}) => {
    try {
      const result = await system.getTimerTaskLogs({
        taskId,
        page: logPagination.current,
        pageSize: logPagination.pageSize,
        ...params,
      });

      if (result.code === 200) {
        setLogList(result.data.list);
        setLogPagination({
          ...logPagination,
          total: result.data.data.pagination.total,
          current: result.data.data.pagination.current,
        });
      }
    } catch (error) {
      message.error("获取任务日志失败");
    }
  };

  // 搜索
  const handleSearch = () => {
    setPagination({ ...pagination, current: 1 });
    fetchTaskList({ page: 1 });
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    setPagination({ ...pagination, current: 1 });
    fetchTaskList({ page: 1 });
  };

  // 打开新增/编辑弹窗
  const handleOpenModal = (task?: any) => {
    setEditingTask(task || null);
    if (task) {
      setSelectedTaskType(task.task_type);
      setIsJavaScriptType(task.task_type === "javascript");

      let taskConfigValue = "";
      if (task.task_config) {
        try {
          // 统一处理：先解析JSON字符串
          const config =
            typeof task.task_config === "string"
              ? JSON.parse(task.task_config)
              : task.task_config;

          if (task.task_type === "javascript") {
            // JavaScript类型提取code字段
            taskConfigValue = config.code || config;
          } else {
            // 其他类型格式化为JSON
            taskConfigValue = JSON.stringify(config, null, 2);
          }
        } catch (e) {
          console.log("JSON解析失败，使用原始值:", e);
          // 解析失败时直接使用原始值
          taskConfigValue = task.task_config;
        }
      }

      taskForm.setFieldsValue({
        ...task,
        task_config: taskConfigValue,
      });
    } else {
      taskForm.resetFields();
      setSelectedTaskType("");
      setIsJavaScriptType(false);
    }
    setModalVisible(true);
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setModalVisible(false);
    setEditingTask(null);
    setSelectedTaskType("");
    setIsJavaScriptType(false);
    taskForm.resetFields();
  };

  // 保存任务
  const handleSaveTask = async () => {
    try {
      await taskForm.validateFields();
      const values = taskForm.getFieldsValue();
      let result;
      if (editingTask) {
        result = await system.updateTimerTask({ ...editingTask, ...values });
      } else {
        result = await system.addTimerTask(values);
      }
      if (result.code === 200) {
        message.success(editingTask ? "更新成功" : "添加成功");
        handleCloseModal();
        fetchTaskList();
        fetchTaskStats();
      } else {
        message.error(result.msg || "操作失败");
      }
    } catch (error) {
      message.error("表单校验失败");
    }
  };

  // 查看日志
  const handleViewLogs = (task: any) => {
    setSelectedTask(task);
    setLogDrawerVisible(true);
    fetchTaskLogs(task.id);
  };

  // 刷新数据
  const handleRefresh = () => {
    fetchTaskList();
    fetchTaskStats();
  };

  // 表格分页变化
  const handleTableChange = (paginationInfo: any) => {
    setPagination(paginationInfo);
    fetchTaskList({
      page: paginationInfo.current,
      pageSize: paginationInfo.pageSize,
    });
  };

  // 日志分页变化
  const handleLogTableChange = (paginationInfo: any) => {
    setLogPagination(paginationInfo);
    if (selectedTask) {
      fetchTaskLogs(selectedTask.id, {
        page: paginationInfo.current,
        pageSize: paginationInfo.pageSize,
      });
    }
  };

  // 常用Cron表达式下拉菜单
  const cronMenuItems: MenuProps["items"] = CommonCronExpressions.map(
    (item, index) => ({
      key: index,
      label: (
        <div
          onClick={() =>
            taskForm.setFieldsValue({ cron_expression: item.value })
          }
        >
          <div style={{ fontWeight: "bold" }}>{item.label}</div>
          <div style={{ fontSize: "12px", color: "#666" }}>{item.value}</div>
        </div>
      ),
    })
  );

  const handleActionClick = async (key: string, record: any) => {
    switch (key) {
      case "execute":
        const executeRes = await system.executeTimerTask({ id: record.id });
        if (executeRes.code === 200) {
          message.success("任务已开始执行");
        } else {
          message.error(executeRes.msg || "执行失败");
        }
        break;
      case "toggle":
        const toggleRes = await system.toggleTimerTask({
          id: record.id,
          status: record.status === 1 ? 0 : 1,
        });
        if (toggleRes.code === 200) {
          message.success("状态切换成功");
          fetchTaskList();
        } else {
          message.error(toggleRes.msg || "状态切换失败");
        }
        break;
      case "delete":
        modal.confirm({
          title: "确认删除",
          content: "确定要删除此任务吗？",
          onOk: async () => {
            const deleteRes = await system.deleteTimerTask({ id: record.id });
            if (deleteRes.code === 200) {
              message.success("删除成功");
              fetchTaskList();
            } else {
              message.error(deleteRes.data.msg || "删除失败");
            }
          },
        });
        break;
      default:
        break;
    }
  };

  return (
    <div className="h-full flex flex-col">
      {/* 统计卡片 */}
      <Row gutter={8} className="mb-2">
        <Col span={4}>
          <Card>
            <Statistic title="任务总数" value={taskStats.totalCount} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="启用任务"
              value={taskStats.activeCount}
              valueStyle={{ color: "#3f8600" }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="停用任务"
              value={taskStats.inactiveCount}
              valueStyle={{ color: "#cf1322" }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="今日执行" value={taskStats.todayExecuteCount} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="今日成功"
              value={taskStats.todaySuccessCount}
              valueStyle={{ color: "#3f8600" }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="今日失败"
              value={taskStats.todayFailCount}
              valueStyle={{ color: "#cf1322" }}
            />
          </Card>
        </Col>
      </Row>

      {/* 主要内容 */}
      <Card size="small">
        {/* 搜索表单 */}
        <div className="flex items-center justify-between">
          <Form
            form={searchForm}
            layout="inline"
            className="mb-2"
            onFinish={handleSearch}
          >
            <Form.Item name="taskName" label="任务名称">
              <Input placeholder="输入任务名称" allowClear />
            </Form.Item>
            <Form.Item name="taskType" label="任务类型">
              <Select
                placeholder="选择任务类型"
                allowClear
                style={{ width: 150 }}
              >
                {taskTypes.map((type) => (
                  <Option key={type.value} value={type.value}>
                    {type.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Select placeholder="选择状态" allowClear style={{ width: 100 }}>
                <Option value={1}>启用</Option>
                <Option value={0}>停用</Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<FilterOutlined />}
                >
                  搜索
                </Button>
                <Button onClick={handleReset}>重置</Button>
              </Space>
            </Form.Item>
          </Form>
          {/* 操作按钮 */}
          <div className="mb-2">
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => handleOpenModal()}
              >
                新增任务
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleRefresh}>
                刷新
              </Button>
            </Space>
          </div>
        </div>
      </Card>
      {/* 任务列表表格 */}
      <Card className="flex-1 mt-2" size="small">
        <Table
          columns={getTableColumns(
            handleOpenModal,
            handleViewLogs,
            handleRefresh
          )}
          dataSource={taskList}
          rowKey="id"
          loading={loading}
          size="small"
          pagination={{
            ...pagination,
            position: ["bottomCenter"],
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          onChange={handleTableChange}
          scroll={{ y: "calc(100vh - 420px)" }}
        />
      </Card>

      {/* 新增/编辑任务弹窗 */}
      <Modal
        title={editingTask ? "编辑任务" : "新增任务"}
        open={modalVisible}
        onOk={handleSaveTask}
        onCancel={handleCloseModal}
        width={800}
      >
        <Form form={taskForm} layout="vertical" initialValues={{ status: 0 }}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="task_name"
                label="任务名称"
                rules={formRules.task_name}
              >
                <Input placeholder="输入任务名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="task_code"
                label="任务编码"
                rules={formRules.task_code}
              >
                <Input placeholder="输入任务编码" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="task_type"
                label="任务类型"
                rules={formRules.task_type}
              >
                <Select
                  placeholder="选择任务类型"
                  onChange={handleTaskTypeChange}
                >
                  {taskTypes.map((type) => (
                    <Option key={type.value} value={type.value}>
                      {type.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="status" label="状态">
                <Select>
                  <Option value={0}>停用</Option>
                  <Option value={1}>启用</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="cron_expression"
            label={
              <Space>
                Cron表达式
                <Dropdown menu={{ items: cronMenuItems }} trigger={["click"]}>
                  <Button type="link" size="small">
                    常用表达式 <DownOutlined />
                  </Button>
                </Dropdown>
                <Button
                  type="link"
                  size="small"
                  icon={<QuestionCircleOutlined />}
                  href="https://crontab.guru/"
                  target="_blank"
                >
                  帮助
                </Button>
              </Space>
            }
            rules={formRules.cron_expression}
          >
            <Input placeholder="输入Cron表达式，如：0 0 * * * (每天0点)" />
          </Form.Item>

          <Form.Item
            name="description"
            label="任务描述"
            rules={formRules.description}
          >
            <TextArea rows={3} placeholder="输入任务描述" />
          </Form.Item>

          <Form.Item
            name="task_config"
            label={
              <Space>
                任务配置
                {selectedTaskType && (
                  <Button
                    type="link"
                    size="small"
                    onClick={() => handleTaskTypeChange(selectedTaskType)}
                  >
                    应用模板
                  </Button>
                )}
              </Space>
            }
            help={
              isJavaScriptType
                ? "请输入JavaScript代码，可以使用console.log()输出日志，用result变量返回结果"
                : "JSON格式的任务配置，根据任务类型填写不同的配置参数"
            }
            rules={getTaskConfigRules(selectedTaskType)}
          >
            {isJavaScriptType ? (
              <TextArea
                rows={8}
                placeholder="console.log('Hello World');
console.log('当前时间:', new Date());
result = '执行成功';"
                style={{
                  fontFamily:
                    'Monaco, Menlo, "Ubuntu Mono", Consolas, source-code-pro, monospace',
                  fontSize: "13px",
                }}
              />
            ) : (
              <TextArea
                rows={6}
                placeholder={
                  selectedTaskType &&
                  TaskConfigTemplates[
                    selectedTaskType as keyof typeof TaskConfigTemplates
                  ]
                    ? JSON.stringify(
                        TaskConfigTemplates[
                          selectedTaskType as keyof typeof TaskConfigTemplates
                        ].config,
                        null,
                        2
                      )
                    : '{"url": "http://example.com/api", "method": "GET"}'
                }
                style={{
                  fontFamily:
                    'Monaco, Menlo, "Ubuntu Mono", Consolas, source-code-pro, monospace',
                  fontSize: "13px",
                }}
              />
            )}
          </Form.Item>
        </Form>
      </Modal>

      {/* 任务日志抽屉 */}
      <Drawer
        title={`任务执行日志 - ${selectedTask?.task_name}`}
        placement="right"
        size="large"
        open={logDrawerVisible}
        onClose={() => setLogDrawerVisible(false)}
      >
        <Table
          columns={getLogTableColumns()}
          dataSource={logList}
          rowKey="id"
          pagination={{
            ...logPagination,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          onChange={handleLogTableChange}
          size="small"
        />
      </Drawer>
    </div>
  );
};

export default function SystemTimer() {
  return (
    <div className="h-full  rounded-[10px] px-2">
      <SystemTimerContent />
    </div>
  );
}
